package com.circus.trace.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.nutz.lang.ContinueLoop;
import org.nutz.lang.Each;
import org.nutz.lang.ExitLoop;
import org.nutz.lang.Lang;
import org.nutz.lang.LoopException;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.circus.trace.TraceApplication;
import com.circus.trace.vo.Flag;
import com.google.common.collect.Lists;

import club.zhcs.captcha.ImageVerification;
import club.zhcs.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 
 * @author kerbores@gmail.com
 *
 */
@Controller
@Api(value = "Index", tags = { "通用" })
public class IndexController {
	Log logger = Logs.get();

	@GetMapping("/captcha")
	@ApiOperation("验证码")
	public void captcha(@RequestParam(value = "length", required = false, defaultValue = "4") @ApiParam(value = "验证码长度", required = false, defaultValue = "4") int length,
			@ApiIgnore HttpServletResponse resp, @ApiIgnore HttpSession session) throws IOException {
		resp.setContentType("image/jpeg");
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0);

		OutputStream out = resp.getOutputStream();
		// 输出图象到页面
		ImageVerification iv = new ImageVerification();

		if (length != 0) {
			iv.setIMAGE_VERIFICATION_LENGTH(length);
		}
		if (ImageIO.write(iv.creatImage(), "JPEG", out)) {
			logger.debug("写入输出流成功:" + iv.getVerifyCode() + ".");
		} else {
			logger.debug("写入输出流失败:" + iv.getVerifyCode() + ".");
		}
		session.setAttribute(TraceApplication.CAPTCHA_KEY, iv.getVerifyCode());
		// 以下关闭输入流！
		out.flush();
		out.close();
	}

	@GetMapping("countries")
	public @ResponseBody Object test() {
		List<NutMap> data = Lists.newArrayList();
		Lang.each(Flag.values(), new Each<Flag>() {

			@Override
			public void invoke(int arg0, Flag flag, int arg2) throws ExitLoop, ContinueLoop, LoopException {
				data.add(Lang.obj2nutmap(flag).addv("orgin", flag.name()));
			}
		});
		return Result.success().addData("countries", data);
	}

}
